<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/ajax.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        form {
            width: 400px;
        }

        label {
            display: inline-block;
            text-align: right;
            width: 120px;
        }

        form>p {
            margin-top: 10px;
        }

        form>p>span {
            position: absolute;
            margin-left: 5px;
        }

        form>p:last-of-type {
            text-align: center;
        }

        .right {
            color: green;
            font-size: 14px;
        }

        .error {
            color: red;
            font-size: 14px;
        }
    </style>
</head>

<body>
    <form onsubmit="return false">
        <p>
            <label for="">用户名:</label>
            <input type="text" class="user">
            <span class="user_span"></span>
        </p>
        <p>
            <label for="">密码:</label>
            <input type="text" class="pwd">
            <span class="pwd_span"></span>
        </p>
        <p>
            <label for="">手机号:</label>
            <input type="text" class="phone">
            <span class="phone_span"></span>
        </p>
        <p>
            <label for="">邮箱:</label>
            <input type="text" class="email">
            <span class="email_span"></span>
        </p>
        <p>
            <input type="submit" class="subBtn" value="注册">
            <input type="reset" class="retBtn" value="取消">
        </p>
    </form>
</body>
<script>
    // 先进行表单验证
    // 用户名   由 数字 大小写字母 下划线 $ 组成, 6-12位,且不能以数字开头

    // 表单验证成功之后  将 user pwd phone emial => 存到cookie中  => 跳转到登录页

    // 封装 setCookie(key,val,day)   
    // getCookie(key) => val;  

    var judgeInpList = document.querySelectorAll("input[type=text]");
    var subBtn = document.querySelector(".subBtn");

    //1. 先判断用户名/手机号/邮箱 格式是否正确
    // 如果格式正确  在判断, 用户名/手机号/邮箱 是否能已存在

    for (let i = 0; i < judgeInpList.length; i++) {
        let inp = judgeInpList[i];
        inp.onchange = function () {
            var con = this.value.trim(); // user  pwd  phone  emial
            var result = judgeRuler(con, i);  // 验证规则
            var tipSpan = next(this);

            if (result.status) { // 规则 正确
                if (i == 1) {  // 密码  =>输出验证规则
                    tipSpan.textContent = result.msg;
                    tipSpan.className = "right";
                } else {
                    judgeExist(con, i, tipSpan);  // 验证是否存在  直接将结果输出到 tipSpan(后期学习Promise之后再次优化) 
                }
            } else {
                tipSpan.textContent = result.msg;
                tipSpan.className = "error";
            }


        }
    }

    subBtn.onclick = function () {
        var list = [...judgeInpList];
        var resultList = list.map(function (inp, i) {   // 循环验证

            var con = inp.value.trim(); // user  pwd  phone  emial
            var result = judgeRuler(con, i);  // 每次验证的结果
            // console.log(result);

            // 每次验证的结果 => 提示
            var tipSpan = next(inp);
            tipSpan.textContent = result.msg;
            tipSpan.className = result.status ? "right" : "error";

            return result;
        })
        console.log(resultList);

        var flag = resultList.every(result => result.status == true);

        if (flag) {
            console.log("可以注册");

            var user = list[0].value;
            var pwd = list[1].value;
            var phone = list[2].value;
            var email = list[3].value;

            $.ajax({
                type: "post",
                url: "../php/register.php",
                data: {
                    user: user,
                    pwd,
                    phone,
                    email,
                },
                dataType: "json",
                success: function (result) {
                    if (result.status) {
                        location.href = "login.html";
                        // console.log("跳转登录");
                    } else {
                        alert(result.msg);
                    }
                }
            })




            // var xhr = new XMLHttpRequest();

            // xhr.open("post", "../php/register.php", true);

            // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            // xhr.send(`user=${user}&pwd=${pwd}&phone=${phone}&email=${email}`);

            // xhr.onreadystatechange = function () {

            //     if (xhr.readyState == 4 && xhr.status == 200) {
            //         console.log(xhr.responseText);
            //         var result = JSON.parse(xhr.responseText);
            //         if (result.status) {
            //             location.href = "login.html";
            //             // console.log("跳转登录");
            //         } else {
            //             alert(result.msg);
            //         }
            //     }

            // }

        }


    }

    function judgeRuler(con, index) {
        var result = {};
        var msgList = ["用户名 由数字,大小写字母,下划线,$ 组成, 6-12位,且不能以数字开头", "密码 由数字,大小写字母,下划线,$ 组成, 6-12位", "手机号格式有误", "请输入正确的邮箱"];
        switch (index) {
            case 0:
                var reg = /^[a-zA-Z_$][\w$]{5,11}$/;
                break;
            case 1:
                var reg = /^[\w$]{6,12}$/;
                break;
            case 2:
                var reg = /^1[2-9]\d{9}$/;
                break;
            case 3:
                // 123132@qq.com
                var reg = /^\w+@\w+\.com$/;
                break;
        }
        if (reg.test(con)) {
            // 密码强度
            if (index == 1) {

                var numReg = /[0-9]/;
                var smallReg = /[a-z]/;
                var bigReg = /[A-Z]/;
                var speReg = /[_$]/;

                var numFlag = numReg.test(con);
                var smallFlag = smallReg.test(con);
                var bigFlag = bigReg.test(con);
                var speFlag = speReg.test(con);

                var sum = numFlag + smallFlag + bigFlag + speFlag;

                result.status = true;
                result.msg = "密码强度:" + sum;
                result.level = sum;

            } else {
                result.status = true;
                result.msg = "√";
            }
        } else {
            result.status = false;
            result.msg = msgList[index];
        }
        return result;
    }

    function judgeExist(con, index, tipSpan) {
        var xhr = new XMLHttpRequest();
        switch (index) {
            case 0:   // 用户名
                // 异步请求  (请求=> 响应需要时间   代码不会等待响应结束之后在 return)
                xhr.open("get", "../php/isExistUser.php?user=" + con, true);
                break;
            case 1:
                return false;
                break;
            case 2:
                // 异步请求  (请求=> 响应需要时间   代码不会等待响应结束之后在 return)
                xhr.open("get", "../php/isExistPhone.php?phone=" + con, true);
                break;
            case 3:
                xhr.open("get", "../php/isExistEmail.php?email=" + con, true);
                break;
        }

        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = JSON.parse(xhr.responseText);
                console.log(result);

                // 将结果 输出到提示框中

                if (result.status) { //true  => 可以注册
                    tipSpan.className = "right";
                    tipSpan.textContent = "√";
                } else {
                    tipSpan.className = "error";
                    tipSpan.textContent = result.msg;
                }
            }
        }

    }



    function judgeExist(con, index, tipSpan) {
        var xhr = new XMLHttpRequest();
        switch (index) {
            case 0:   // 用户名
                // 异步请求  (请求=> 响应需要时间   代码不会等待响应结束之后在 return)
                xhr.open("get", "../php/isExistUser.php?user=" + con, true);
                break;
            case 1:
                return false;
                break;
            case 2:
                // 异步请求  (请求=> 响应需要时间   代码不会等待响应结束之后在 return)
                xhr.open("get", "../php/isExistPhone.php?phone=" + con, true);
                break;
            case 3:
                xhr.open("get", "../php/isExistEmail.php?email=" + con, true);
                break;
        }

        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var result = JSON.parse(xhr.responseText);
                console.log(result);

                // 将结果 输出到提示框中

                if (result.status) { //true  => 可以注册
                    tipSpan.className = "right";
                    tipSpan.textContent = "√";
                } else {
                    tipSpan.className = "error";
                    tipSpan.textContent = result.msg;
                }
            }
        }

    }


    function next(ele) {
        return ele.nextElementSibling || ele.nextSibling;
    }



    function setCookie(key, value, day) {
        if (day) {   // 有效期

            var date = new Date();
            date.setDate(date.getDate() + day);
            document.cookie = key + "=" + value + ";expires=" + date.toUTCString() + ";path=/";
        } else {  // 浏览器会话结束
            document.cookie = key + "=" + value + ";path=/";
        }
    }







</script>

</html>